#include "core/logger_config.hpp"
#include <fstream>
#include <iostream>


namespace { // 使用匿名命名空间
    void parse_config(LoggerConfig& config, const nlohmann::json& j) {
        // ... 将 fromJsonFile 中所有的 if(j.contains(...)) 解析逻辑全部移到这里 ...
        // 例如：
        // 加载级别配置
        if (j.contains("level") && j["level"].is_string()) {
            std::string level_str = j["level"];
            if (level_str == "trace") config.level.default_level = LogLevel::Trace;
            else if (level_str == "debug") config.level.default_level = LogLevel::Debug;
            else if (level_str == "info") config.level.default_level = LogLevel::Info;
            else if (level_str == "warn") config.level.default_level = LogLevel::Warn;
            else if (level_str == "error") config.level.default_level = LogLevel::Error;
            else if (level_str == "critical") config.level.default_level = LogLevel::Critical;
            else if (level_str == "off") config.level.default_level = LogLevel::Off;
        }

        // 加载异步配置
        if (j.contains("async")) {
            auto& async_j = j["async"];
            if (async_j.contains("main_queue_size"))
                config.async.main_queue_size = async_j["main_queue_size"];
            if (async_j.contains("fallback_queue_size"))
                config.async.fallback_queue_size = async_j["fallback_queue_size"];
            if (async_j.contains("flush_interval_ms"))
                config.async.flush_interval = std::chrono::milliseconds(async_j["flush_interval_ms"]);
            if (async_j.contains("queue_space_threshold"))
                config.async.queue_space_threshold = async_j["queue_space_threshold"];
            if (async_j.contains("fallback_batch_size"))
                config.async.fallback_batch_size = async_j["fallback_batch_size"];
        }

        // 加载控制台配置
        if (j.contains("console")) {
            auto& console_j = j["console"];
            if (console_j.contains("enabled"))
                config.console.enabled = console_j["enabled"];
            if (console_j.contains("logger_name"))
                config.console.logger_name = console_j["logger_name"];
            if (console_j.contains("apply_filtering"))
                config.console.apply_filtering = console_j["apply_filtering"];
        }

        // 加载文件配置
        if (j.contains("file")) {
            auto& file_j = j["file"];
            if (file_j.contains("enabled"))
                config.file.enabled = file_j["enabled"];
            if (file_j.contains("filename"))
                config.file.filename = file_j["filename"];
            if (file_j.contains("max_size"))
                config.file.max_size = file_j["max_size"];
            if (file_j.contains("max_files"))
                config.file.max_files = file_j["max_files"];
            if (file_j.contains("logger_name"))
                config.file.logger_name = file_j["logger_name"];
        }

        // 加载网络配置
        if (j.contains("network")) {
            auto& network_j = j["network"];
            if (network_j.contains("enabled"))
                config.network.enabled = network_j["enabled"];
            if (network_j.contains("url"))
                config.network.url = network_j["url"];
            if (network_j.contains("timeout"))
                config.network.timeout = network_j["timeout"];
            if (network_j.contains("connect_timeout"))
                config.network.connect_timeout = network_j["connect_timeout"];
            if (network_j.contains("thread_pool_size"))
                config.network.thread_pool_size = network_j["thread_pool_size"];
        }

        // 加载过滤器配置
        if (j.contains("filter")) {
            auto& filter_j = j["filter"];
            if (filter_j.contains("enabled"))
                config.filter.enabled = filter_j["enabled"];
            if (filter_j.contains("filters") && filter_j["filters"].is_array()) {
                config.filter.filters.clear();
                for (const auto& filter : filter_j["filters"]) {
                    if (filter.contains("pattern") && filter.contains("replacement")) {
                        config.filter.filters.emplace_back(
                            filter["pattern"].get<std::string>(),
                            filter["replacement"].get<std::string>()
                        );
                    }
                }
            }
        }

        // 加载回溯配置
        if (j.contains("backtrace")) {
            auto& backtrace_j = j["backtrace"];
            if (backtrace_j.contains("enabled"))
                config.backtrace.enabled = backtrace_j["enabled"];
            if (backtrace_j.contains("size"))
                config.backtrace.size = backtrace_j["size"];
        }

        // 加载格式化器配置
        if (j.contains("formatter")) {
            auto& formatter_j = j["formatter"];
            if (formatter_j.contains("type")) {
                std::string type = formatter_j["type"];
                if (type == "json")
                     config.formatter.type = FormatterConfig::Type::JSON;
                else if (type == "basic")
                    config.formatter.type = FormatterConfig::Type::Basic;
            }
        }


        // 加载Metrics配置解析
        if (j.contains("metrics")) {
            auto& metrics_j = j["metrics"];
            if (metrics_j.contains("enabled")) {
                config.metrics.enabled = metrics_j["enabled"];
            }
            if (metrics_j.contains("logger_name")) {
                config.logger_name = metrics_j["logger_name"];
            }
        }
        
    }
}

LoggerConfig LoggerConfig::fromJsonFile(const std::string& filepath) {
    LoggerConfig config;
    try {
        std::ifstream file(filepath);
        if (!file.is_open()) {
            std::cerr << "Warning: Could not open config file: " << filepath << std::endl;
            return config;
        }
        
        nlohmann::json j;
        file >> j;
        
        parse_config(config, j);

    } catch (const std::exception& e) {
        std::cerr << "Error loading config: " << e.what() << std::endl;
    }
    
    return config;
}

LoggerConfig LoggerConfig::fromJsonString(const std::string& json_str) {
    LoggerConfig config;
    try {
        nlohmann::json j = nlohmann::json::parse(json_str);
        parse_config(config, j);
    } catch (const std::exception& e) {
        std::cerr << "Error parsing JSON string: " << e.what() << std::endl;
    }
    return config;
}

nlohmann::json LoggerConfig::toJson() const {
    nlohmann::json j;
    
    // 导出级别配置
    std::string level_str;
    switch (level.default_level) {
        case LogLevel::Trace: level_str = "trace"; break;
        case LogLevel::Debug: level_str = "debug"; break;
        case LogLevel::Info: level_str = "info"; break;
        case LogLevel::Warn: level_str = "warn"; break;
        case LogLevel::Error: level_str = "error"; break;
        case LogLevel::Critical: level_str = "critical"; break;
        case LogLevel::Off: level_str = "off"; break;
    }
    j["level"] = level_str;
    
    // 导出异步配置
    j["async"]["main_queue_size"] = async.main_queue_size;
    j["async"]["fallback_queue_size"] = async.fallback_queue_size;
    j["async"]["flush_interval_ms"] = async.flush_interval.count();
    j["async"]["queue_space_threshold"] = async.queue_space_threshold;
    j["async"]["fallback_batch_size"] = async.fallback_batch_size;
    
    // 导出控制台配置
    j["console"]["enabled"] = console.enabled;
    j["console"]["logger_name"] = console.logger_name;
    j["console"]["apply_filtering"] = console.apply_filtering;
    
    // 导出文件配置
    j["file"]["enabled"] = file.enabled;
    j["file"]["filename"] = file.filename;
    j["file"]["max_size"] = file.max_size;
    j["file"]["max_files"] = file.max_files;
    j["file"]["logger_name"] = file.logger_name;
    
    // 导出网络配置
    j["network"]["enabled"] = network.enabled;
    j["network"]["url"] = network.url;
    j["network"]["timeout"] = network.timeout;
    j["network"]["connect_timeout"] = network.connect_timeout;
    j["network"]["thread_pool_size"] = network.thread_pool_size;
    
    // 导出过滤器配置
    j["filter"]["enabled"] = filter.enabled;
    nlohmann::json filters_array = nlohmann::json::array();
    for (const auto& [pattern, replacement] : filter.filters) {
        filters_array.push_back({
            {"pattern", pattern},
            {"replacement", replacement}
        });
    }
    j["filter"]["filters"] = filters_array;
    
    // 导出回溯配置
    j["backtrace"]["enabled"] = backtrace.enabled;
    j["backtrace"]["size"] = backtrace.size;
    
    // 导出格式化器配置
    j["formatter"]["type"] = (formatter.type == FormatterConfig::Type::JSON) ? "json" : "basic";
    
    return j;
}

